﻿module Sustainalytics.Claims {

    import Common = Sustainalytics.Common;

    export class ClaimsAuthorizationService implements IClaimsAuthorizationService {
        private staticObjects: Common.IStaticObjects;
        constructor(staticObjects: Common.IStaticObjects) {
            this.Validate;
            this.staticObjects = staticObjects;
        }

        public Validate(resource: string, verb: string, parameters: ResourceParameters[]): boolean {
            var result = false;
            if (this.staticObjects.resourcePermissions == "") {
                // fall to backup in case resourcePermissions got reset
                this.staticObjects.resourcePermissions = localStorage.getItem("sust:a:ur");
            }

            if (this.staticObjects.resourcePermissions != "") {

                var resources = angular.fromJson(this.staticObjects.resourcePermissions);

                if (!resources) {
                    return false;
                }

                $.each(resources, (index: number, value: string) => {
                    var _value = <ActiveResourcesDto>angular.fromJson(value);

                    var sortedRequestParameters;
                    if (parameters != null) {
                        sortedRequestParameters = parameters.sort((a, b) => { return a.key.charCodeAt(0) - b.key.charCodeAt(0) });
                    }
                    else {
                        sortedRequestParameters = [];
                    }

                    var sortedResourceParameters;
                    if (_value.parameters != null) {
                        sortedResourceParameters = _value.parameters.sort((a, b) => { return a.key.charCodeAt(0) - b.key.charCodeAt(0) });
                    }
                    else {
                        sortedResourceParameters = [];
                    }

                    if ((_value.resource.toLowerCase() == resource.toLowerCase()) &&
                        (_value.verb.toLowerCase() == verb.toLowerCase()) &&
                        (angular.equals(sortedRequestParameters, sortedResourceParameters))) {
                        result = true;
                        return false;
                    }
                });
            }
            return result;
        }
    }

    var claimsAuthorizationService = angular.module('Sustainalytics.Claims');

    claimsAuthorizationService.factory('ClaimsAuthorizationService', function (staticObjects) {
        var claimsAuthorizeService = new Sustainalytics.Claims.ClaimsAuthorizationService(staticObjects);

        return claimsAuthorizeService;
    });
} 
